package top.lucas9.wechat.push.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import top.lucas9.wechat.push.common.WeatherApiEnum;
import top.lucas9.wechat.push.config.WeatherApiProperties;
import top.lucas9.wechat.push.entity.WeatherDayResult;
import top.lucas9.wechat.push.entity.WeatherNowResult;
import top.lucas9.wechat.push.entity.WeatherResult;
import top.lucas9.wechat.push.service.WeatherRequestService;

import java.util.Objects;

/**
 * 天气请求
 *
 * @author lucas9
 * @date 2024/10/12 0:40
 */
@Service
public class WeatherRequestServiceImpl implements WeatherRequestService {
    private final WeatherApiProperties weatherApiProperties;

    public WeatherRequestServiceImpl(WeatherApiProperties weatherApiProperties) {
        this.weatherApiProperties = weatherApiProperties;
    }


    @Override
    public WeatherDayResult getCityDaysWeather(WeatherApiEnum apiEnum, String latitude, String longitude) {
        return doRequest(weatherApiProperties.getCityRequestUrl(), apiEnum, latitude, longitude, WeatherDayResult.class);
    }

    @Override
    public WeatherNowResult getCityNowWeather(String latitude, String longitude) {
        return doRequest(weatherApiProperties.getCityRequestUrl(), WeatherApiEnum.NOW, latitude, longitude, WeatherNowResult.class);
    }

    @Override
    public WeatherDayResult getGridDaysWeather(WeatherApiEnum apiEnum, String latitude, String longitude) {
        return doRequest(weatherApiProperties.getGridRequestUrl(), apiEnum, latitude, longitude, WeatherDayResult.class);
    }

    @Override
    public WeatherNowResult getGridNowWeather(String latitude, String longitude) {
        return doRequest(weatherApiProperties.getGridRequestUrl(), WeatherApiEnum.NOW, latitude, longitude, WeatherNowResult.class);
    }

    /**
     * 发送请求
     *
     * @param requestUrl
     * @param apiEnum
     * @param latitude
     * @param longitude
     * @param resultType
     * @param <T>
     * @return
     */
    private <T> T doRequest(String requestUrl, WeatherApiEnum apiEnum, String latitude, String longitude, Class<T> resultType) {
        String url = String.format("%s/%s?location=%s,%s&key=%s&lang=%s", requestUrl,
                apiEnum.getApi(),
                latitude,
                longitude,
                weatherApiProperties.getKey(),
                weatherApiProperties.getLang());
        String response = HttpUtil.get(url);
        T result = JSONUtil.toBean(response, resultType);
        if (result != null && resultType.isAssignableFrom(WeatherResult.class)) {
            WeatherResult weatherResult = (WeatherResult) result;
            Assert.isTrue(Objects.equals(weatherResult.getCode(), WeatherNowResult.SUCCESS_CODE), "获取天气失败");
        }
        return result;
    }
}
